package com.sky.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.mapper.UserMapper;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author luo20
 * @description 针对表【user(用户信息)】的数据库操作Service实现
 * @createDate 2025-07-18 01:56:57
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    // 微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 调用微信接口服务，获取当前用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        // 判断openid是否为空，如果为空则表示登录失败，抛出业务异常
        if (StringUtils.isBlank(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        // 如果是新用户，自动完成注册
        if (ObjectUtils.isEmpty(user)) {
            user = new User()
                    .setOpenid(openid)
                    .setCreateTime(LocalDateTime.now());
           Integer result = userMapper.insertUser(user);
           if (result <= 0) {
               throw new LoginFailedException(MessageConstant.NEW_USER_LOGIN_FAILED);
           }
        }
        // 返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务，获取当前用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("appid", weChatProperties.getAppid());
            map.put("secret", weChatProperties.getSecret());
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");

            String json = HttpClientUtil.doGet(WX_LOGIN, map);

            // 检查响应是否为空
            if (json == null || json.trim().isEmpty()) {
                throw new RuntimeException("微信API响应为空，可能是网络连接问题");
            }

            JSONObject jsonObject = JSONObject.parseObject(json);

            // 检查微信API是否返回错误
            String errcode = jsonObject.getString("errcode");
            if (errcode != null) {
                String errmsg = jsonObject.getString("errmsg");
                throw new RuntimeException("微信登录失败：" + errcode + " - " + errmsg);
            }

            String openid = jsonObject.getString("openid");
            if (openid == null || openid.trim().isEmpty()) {
                throw new RuntimeException("微信API未返回openid");
            }

            return openid;

        } catch (Exception e) {
            // 记录详细错误信息
            System.err.println("微信登录失败：" + e.getMessage());
            e.printStackTrace();

            // 可以根据需要返回null或抛出自定义异常
            throw new RuntimeException("微信登录服务暂时不可用，请稍后重试", e);
        }
    }
}




